package com.pcbly.web.components.form;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.pcbly.web.bean.table.TableBean;   
import com.pcbly.web.business.table.TableService;
import com.pcbly.web.components.utils.random.GUID; 

public class AnalyseRequestData {

	private String formId;

	private String data; 
	
	private TableService tableService;
	
	private String formTableId; 
	protected static final Log log = LogFactory
	.getLog(AnalyseRequestData.class);
	

	public String getFormTableId() {
		return formTableId;
	}

	public void setFormTableId(String formTableId) {
		this.formTableId = formTableId;
	}

	public HashMap<String, String> analyseData() throws Exception {
		if (data == null || "".equals(data.trim())) {
			return null;
		} else {
			data = data.trim();
			 data = data.substring(0, data.length());
			 System.out.println("data::::::::::::"+data);
			 log.debug("data::::::::::::"+data);
			String[] columnAndDatas = data.split("::::::");// 解析客户提交的数据
			List<String> columns = new ArrayList<String>();
			List<String> datas = new ArrayList<String>();
			for (String columnAndData : columnAndDatas) {// 分离数据，字段名称和数据
//				 System.out.println("columnAndData::::::::::::"+columnAndData);
//				 log.debug("columnAndData::::::::::::"+columnAndData);
				String[] splitColumnAndData = columnAndData.split(";;;;;;");
//				 System.out.println("splitColumnAndData[0]::::::::::::"+splitColumnAndData[0]);
//				 System.out.println("splitColumnAndData.length::::::::::::"+splitColumnAndData.length);
//				 log.debug("splitColumnAndData.length::::::::::::"+splitColumnAndData.length);
				if (splitColumnAndData.length == 2) {
					columns.add(splitColumnAndData[0].trim());
//					 System.out.println("splitColumnAndData[0]::::::::::::"+splitColumnAndData[0]);
//					 log.debug("splitColumnAndData[0]::::::::::::"+splitColumnAndData[0]);
//					 System.out.println("splitColumnAndData[1]::::::::::::"+splitColumnAndData[1]);
//					 log.debug("splitColumnAndData[1]::::::::::::"+splitColumnAndData[1]);
					datas.add(splitColumnAndData[1].trim());
				} else {
					columns.add(splitColumnAndData[0].trim());
					datas.add("");
				}
			}
			String keys = "0";
			for (String column : columns) {// 查询关键字
//				 System.out.println("column::::::::::::"+column);
//				 log.debug("column::::::::::::"+column);
				String[] columnKeys = column.split("\\_");
//				System.out.println("columnKeys length::::::::::::"+columnKeys.length);
//				log.debug("columnKeys length::::::::::::"+columnKeys.length);
//				System.out.println("columnKeys::::::::::::"+columnKeys[0]);
//				log.debug("columnKeys::::::::::::"+columnKeys[0]);
				if (!(keys.indexOf(columnKeys[1]) >= 0)) {
					keys = keys + ";;" + column;
				}
			}
			String[] keyArray = keys.split(";;");
			String tableIds = keys;
			tableIds = tableIds.replaceAll(";;id_", ",");
//			 System.out.println("tableIds::::::::::::"+tableIds);
//			 log.debug("tableIds::::::::::::"+tableIds);
//			 if(true){
//			 return null;
//			 } 
			List<TableBean> tableBeans = tableService
					.findTableBeansByTableIds(tableIds);

			HashMap<String, HashMap<String, String>> map = new HashMap<String, HashMap<String, String>>();
			for (int i = 1; i < keyArray.length; i++) {// 把数据都保存在hashmap里面
				String key = keyArray[i];
//				 System.out.println("key::::::::::::"+key);
//				 log.debug("key::::::::::::"+key);
				String temp = key.substring(3, key.length());
//				 System.out.println("temp::::::::::::"+temp);
//				 log.debug("temp::::::::::::"+temp);
				HashMap<String, String> tmap = new HashMap<String, String>();
				for (int j = 0; j < columns.size(); j++) {
					String column = columns.get(j);
//					 System.out.println("column::::::::::::"+column);
//					 log.debug("column::::::::::::"+column);
					if (column.indexOf(temp) >= 0) {
						column = column.substring(0, column.indexOf("_"));
//						 System.out.println("column::::::::::::"+column);
//						 log.debug("column::::::::::::"+column);
//						 System.out.println("datas.get("+j+")::::::::::::"+datas.get(j));
//						 log.debug("datas.get("+j+")::::::::::::"+datas.get(j));
						tmap.put(column, datas.get(j));
					}
				}
				map.put(key, tmap);
			}

			Set<String> set = map.keySet();
			HashMap<String, HashMap<String, String>> lastDataMap = new HashMap<String, HashMap<String, String>>();
			for (TableBean table : tableBeans) {
				Iterator<String> it = set.iterator();
				while (it.hasNext()) {
					String keyTable = it.next();
					if ((keyTable).indexOf(table.getId()) >= 0) {
						lastDataMap.put(table.getTableName() + "_"
								+ table.getId(), map.get(keyTable));
						break;
					}
				}
			}
			HashMap<String, String> sqlMap = hashMaptosqlHashMap(lastDataMap);
			return sqlMap;
		}

	}

	private HashMap<String, String> hashMaptosqlHashMap(
			HashMap<String, HashMap<String, String>> map) {
		Set<String> set = map.keySet();
		Iterator<String> it = set.iterator();
		HashMap<String, String> sqlMap = new HashMap<String, String>(); 
		while (it.hasNext()) {// 装配sql语句。
			String keyTable = it.next();
			String tableKeys0 = keyTable
					.substring(0, keyTable.lastIndexOf("_"));
			String tableKeys1 = keyTable.substring(keyTable.lastIndexOf("_")+1,
					keyTable.length());
			 System.out.println("keyTable::::::::::::"+keyTable);
			 log.debug("keyTable::::::::::::"+keyTable);
			 System.out.println("tableKeys0::::::::::::"+tableKeys0);
			 log.debug("tableKeys0::::::::::::"+tableKeys0);
			 System.out.println("tableKeys1::::::::::::"+tableKeys1);
			 log.debug("tableKeys1::::::::::::"+tableKeys1); 
			HashMap<String, String> tmap = map.get(keyTable);
			String id = tmap.get("id");
			String sql = "";
			if (id == null || "".equals(id.trim())) {// 插入语句拼凑
				sql = sql + "insert into " + tableKeys0;
				Set<String> tset = tmap.keySet();
				Iterator<String> tit = tset.iterator();
				String columnstring = "";
				String valuestring = "";
				while (tit.hasNext()) {// 插入语句主体
					String tcolumn = tit.next();
					String tvalue = tmap.get(tcolumn);
					if (!(tcolumn.equals("id"))) {
						columnstring = columnstring + "" + tcolumn + ",";
						if (tvalue == null || "".equals(tvalue.trim())) {
							valuestring = valuestring + "'null',";
						} else {
							tvalue = tvalue.replaceAll("'", "''");
							valuestring = valuestring + "'" + tvalue + "',";
						}

					}
				}
				columnstring = columnstring + "id";
				id = (new GUID()).toString();
				valuestring = valuestring + "'" + id + "'";
				sql = sql + "(" + columnstring + ")values(" + valuestring + ")";
//				 System.out.println("sql::::::::::::"+sql);
//				 log.debug("sql::::::::::::"+sql);

				valuestring = "insert into t_form_table_data (FORMID,TABLEID,KEYID,ID)values(";
				valuestring = valuestring + "'" + formId + "',";
				valuestring = valuestring + "'" + tableKeys1 + "',";
				valuestring = valuestring + "'" + id + "',";

				valuestring = valuestring + "'" + formTableId + "')";
				sqlMap.put("t_form_table_data", valuestring);
				sqlMap.put(tableKeys0, sql);
			} else {// 修改语句拼凑
				sql = sql + "update " + tableKeys0 + " set ";
				Set<String> tset = tmap.keySet();
				Iterator<String> tit = tset.iterator();
				String valuestring = "";
				while (tit.hasNext()) {// 修改语句主体
					String tcolumn = tit.next();
					String tvalue = tmap.get(tcolumn);
					if (!(tcolumn.equals("id"))) {
						if (tvalue == null || "".equals(tvalue.trim())) {
							valuestring = valuestring + tcolumn + "='null' ,";
						} else {
							tvalue = tvalue.replaceAll("'", "''");
							valuestring = valuestring + tcolumn + "='" + tvalue
									+ "' ,";
						}

					}
				}
				valuestring = valuestring
						.substring(0, valuestring.length() - 1);
				valuestring = valuestring + " where id='" + id + "'";
				sql = sql + valuestring;
				sqlMap.put(tableKeys0, sql);
			}
		}
		Set<String> tset = sqlMap.keySet();
		Iterator<String> tit = tset.iterator();
		while(tit.hasNext()){
			System.out.println("sql::::::::::::"+sqlMap.get(tit.next()));
		}
		return sqlMap;
	}  

	public String getFormId() {
		return formId;
	}

	public void setFormId(String formId) {
		this.formId = formId;
	}

	public String getData() {
		return data;
	}

	public void setData(String data) {
		this.data = data;
	}

	public TableService getTableService() {
		return tableService;
	}

	public void setTableService(TableService tableService) {
		this.tableService = tableService;
	}

}
